<?php
require_once("../config/dbconn.php");
set_time_limit(0);
$caiwu = $db->get_all("SELECT count(userid) as num,userid,price from wd_caiwu where addtime>1528387200 and ptype=4 and type=1 GROUP BY userid ORDER BY num DESC limit 0,500");
//dump($caiwu);
foreach ($caiwu as $key=>$value){
    if($value['num']==1){
        continue;
    }
    if($value['num']>=2){
        echo $key."错误：".$value['num'].",".$value['userid'].",".$value['price']."<br/>";
        //该会员数据库记录次数
        $num = $value['num'];
        //需要删除的次数
        $up_num = $num-1;
        //需要扣除的金额
        $up_money = $up_num * $value['price'];
        //查询该会员算力钱包余额是否充足
        $user=$db->get_one("select id,username,slprice from wd_users where id={$value['userid']}");
        //余额不足
        if($user['slprice'] <$up_money){
            file_put_contents('./abnormal_member.txt', "余额不足会员:".$user['username']."，算力钱包剩余:".$user['slprice']."需扣除金额：".$up_money."-------".PHP_EOL,FILE_APPEND);
            continue;
        }
        //余额充足
        $db->query('start transaction');#开启事物
        try {
            //更新该会员算力钱包余额
            $row = $db->query("update wd_users set slprice=slprice-{$up_money},ljslprice=ljslprice={$up_money} where id={$value['userid']}");
            //异常
            if(empty($row)){
                throw new Exception('更新失败');
            }
            #会员资金更新成功，删除财务记录
            file_put_contents('./update.sql', "update wd_users set slprice=slprice-{$up_money},ljslprice=ljslprice={$up_money} where id={$value['userid']};".PHP_EOL,FILE_APPEND);
            //查询出该会员今天的所有算力钱包动态奖记录
            $caiwusql="select id,userid,price from wd_caiwu where userid={$value['userid']} and addtime>1528387200 and ptype=4 and type=1 order by addtime desc";
            $caiwu_lst=$db->get_all($caiwusql);

            foreach ($caiwu_lst as $caiwu_key => $caiwu_value){
                if($caiwu_key == $num-1 ){
                    break;
                }
                $rs = $db->query("delete from wd_caiwu where id={$caiwu_value['id']}");
                if(empty($rs)){
                    throw new Exception('财务记录删除失败');
                }
                //记录删除的订单sql
                file_put_contents('./delete_caiwu.sql', "delete from wd_caiwu where id={$caiwu_value['id']};".PHP_EOL,FILE_APPEND);

            }
            $db->query('commit');#提交
        }catch(Exception $e){
            $db->query('rollback');#回滚
            returnJson(0,$e->getMessage());
        }
    }
}
